package com.chg.mymvc.dao;

import com.chg.mymvc.entity.User;
import com.fJdbcUtil.util.FJdbc;

import java.util.HashMap;
import java.util.List;

public class UserDaoImpl implements UserDao{
    @Override
    public void delUser(int id) {
        String sql="delete from user where id=?";
        Object[] objs = new Object[1];
        objs[0]=id;
        FJdbc.update(sql,objs);
    }

    @Override
    public void updateUser(User user) {
        String sql="update user set name=?,password=? where id=?";
        Object[] objs = new Object[3];
        objs[0]=user.getName();
        objs[1]=user.getPassword();
        objs[2]=user.getId();
        FJdbc.update(sql,objs);
    }

    @Override
    public List<User> queryAll(int page, int pagesize) {
        String sql="select id,name,password from user limit ?,?";
        Object[] params=new Object[]{(page-1)*pagesize,pagesize};
        return FJdbc.queryList(sql,User.class,params);
    }

    @Override
    public User getUserByName(String name) {
      String sql="select id,name,password from user where name=?";
      Object[] params=new Object[]{name};
       return FJdbc.queryOne(sql,User.class,params);
    }

    @Override
    public User getUsersByName(String name) {
        String sql="select id,name,password from user where name like ?";
        Object[] params=new Object[]{"%"+name+"%"};
        return FJdbc.queryOne(sql,User.class,params);
    }

    @Override
    public int addUser(User user) {

            String sql="insert into user(name,password) values(?,?)";
            Object[] objs = new Object[2];
            objs[0]=user.getName();
            objs[1]=user.getPassword();
            FJdbc.update(sql, objs);
            return 1;

    }

    @Override
    public User selecUsertById(int id) {
        String sql="select id,name,password from user where id=?";
        Object[] objs = new Object[1];
        objs[0]=id;
       return FJdbc.queryOne(sql,User.class,objs);
    }
//计算总共条数
    @Override
    public int allcount() {
        String sql="select count(id) from user";
        HashMap<String,Object> map = FJdbc.queryOne(sql, HashMap.class);
        long count = (long)map.get("count(id)");
        return new Long(count).intValue();
    }
}
